<template>
  <div class="performance-monitor-chart">
    <div class="chart-header">
      <div class="chart-controls">
        <el-radio-group v-model="selectedMetric" size="small" @change="updateChart">
          <el-radio-button label="responseTime">响应时间</el-radio-button>
          <el-radio-button label="throughput">吞吐量</el-radio-button>
          <el-radio-button label="errorRate">错误率</el-radio-button>
          <el-radio-button label="cpuUsage">CPU使用率</el-radio-button>
        </el-radio-group>
      </div>
      <div class="chart-legend">
        <div class="legend-item">
          <div class="legend-color response-time"></div>
          <span>响应时间 (ms)</span>
        </div>
        <div class="legend-item">
          <div class="legend-color throughput"></div>
          <span>吞吐量 (req/s)</span>
        </div>
        <div class="legend-item">
          <div class="legend-color error-rate"></div>
          <span>错误率 (%)</span>
        </div>
        <div class="legend-item">
          <div class="legend-color cpu-usage"></div>
          <span>CPU使用率 (%)</span>
        </div>
      </div>
    </div>
    <div ref="chart" class="chart-container"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'PerformanceMonitorChart',
  props: {
    chartData: {
      type: Object,
      required: true
    },
    timeRange: {
      type: String,
      default: '1h'
    },
    autoRefresh: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      chartInstance: null,
      selectedMetric: 'responseTime',
      updateTimer: null
    };
  },
  mounted() {
    this.initChart();
    this.startAutoUpdate();
  },
  beforeUnmount() {
    this.stopAutoUpdate();
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
  watch: {
    chartData: {
      handler() {
        this.updateChart();
      },
      deep: true
    },
    autoRefresh(newVal) {
      if (newVal) {
        this.startAutoUpdate();
      } else {
        this.stopAutoUpdate();
      }
    }
  },
  methods: {
    initChart() {
      if (!this.$refs.chart) return;
      
      this.chartInstance = echarts.init(this.$refs.chart);
      this.updateChart();
      
      // 响应式处理
      window.addEventListener('resize', this.handleResize);
    },
    
    updateChart() {
      if (!this.chartInstance) return;
      
      const option = this.getChartOption();
      this.chartInstance.setOption(option, true);
    },
    
    getChartOption() {
      const { timestamps, responseTime, throughput, errorRate, cpuUsage } = this.chartData;
      
      const series = [
        {
          name: '响应时间',
          type: 'line',
          data: responseTime,
          smooth: true,
          showSymbol: false,
          lineStyle: {
            color: '#667eea',
            width: 3
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(102, 126, 234, 0.3)' },
              { offset: 1, color: 'rgba(102, 126, 234, 0.05)' }
            ])
          },
          emphasis: {
            focus: 'series'
          }
        },
        {
          name: '吞吐量',
          type: 'line',
          data: throughput,
          smooth: true,
          showSymbol: false,
          lineStyle: {
            color: '#f093fb',
            width: 3
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(240, 147, 251, 0.3)' },
              { offset: 1, color: 'rgba(240, 147, 251, 0.05)' }
            ])
          },
          emphasis: {
            focus: 'series'
          }
        },
        {
          name: '错误率',
          type: 'line',
          data: errorRate,
          smooth: true,
          showSymbol: false,
          lineStyle: {
            color: '#4facfe',
            width: 3
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(79, 172, 254, 0.3)' },
              { offset: 1, color: 'rgba(79, 172, 254, 0.05)' }
            ])
          },
          emphasis: {
            focus: 'series'
          }
        },
        {
          name: 'CPU使用率',
          type: 'line',
          data: cpuUsage,
          smooth: true,
          showSymbol: false,
          lineStyle: {
            color: '#fa709a',
            width: 3
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(250, 112, 154, 0.3)' },
              { offset: 1, color: 'rgba(250, 112, 154, 0.05)' }
            ])
          },
          emphasis: {
            focus: 'series'
          }
        }
      ];
      
      return {
        backgroundColor: 'transparent',
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e2e8f0',
          borderWidth: 1,
          textStyle: {
            color: '#1f2937'
          },
          formatter: (params) => {
            let result = `<div style="font-weight: 600; margin-bottom: 8px;">${params[0].axisValue}</div>`;
            params.forEach(param => {
              const color = param.color;
              const value = param.value;
              const name = param.seriesName;
              let unit = '';
              
              if (name === '响应时间') unit = 'ms';
              else if (name === '吞吐量') unit = 'req/s';
              else if (name === '错误率') unit = '%';
              else if (name === 'CPU使用率') unit = '%';
              
              result += `
                <div style="display: flex; align-items: center; margin: 4px 0;">
                  <span style="display: inline-block; width: 12px; height: 12px; background: ${color}; border-radius: 50%; margin-right: 8px;"></span>
                  <span style="flex: 1;">${name}:</span>
                  <span style="font-weight: 600; color: ${color};">${value}${unit}</span>
                </div>
              `;
            });
            return result;
          }
        },
        legend: {
          show: false
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timestamps,
          axisLine: {
            lineStyle: {
              color: '#e2e8f0'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#64748b',
            fontSize: 12,
            formatter: (value) => {
              return value.split(':').slice(0, 2).join(':');
            }
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              color: '#f1f5f9',
              type: 'dashed'
            }
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#64748b',
            fontSize: 12
          }
        },
        series: series,
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicOut'
      };
    },
    
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    
    startAutoUpdate() {
      if (this.autoRefresh && !this.updateTimer) {
        this.updateTimer = setInterval(() => {
          this.updateChart();
        }, 5000); // 每5秒更新一次
      }
    },
    
    stopAutoUpdate() {
      if (this.updateTimer) {
        clearInterval(this.updateTimer);
        this.updateTimer = null;
      }
    }
  }
};
</script>

<style scoped>
.performance-monitor-chart {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 8px;
}

.chart-controls {
  display: flex;
  align-items: center;
}

.chart-legend {
  display: flex;
  gap: 16px;
  align-items: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #64748b;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.legend-color.response-time {
  background: #667eea;
}

.legend-color.throughput {
  background: #f093fb;
}

.legend-color.error-rate {
  background: #4facfe;
}

.legend-color.cpu-usage {
  background: #fa709a;
}

.chart-container {
  flex: 1;
  min-height: 300px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .chart-legend {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .legend-item {
    font-size: 11px;
  }
}
</style> 